package com.example.dou2204.frag.home;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.dou2204.R;
import com.example.dou2204.adapter.CommentAdapter;
import com.example.dou2204.adapter.TuiVideoAdapter;
import com.example.dou2204.baseMVVM.BaseFragment;
import com.example.dou2204.databinding.FragmentTuijianBinding;
import com.example.dou2204.entity.CommentEntity;
import com.example.dou2204.entity.ResultEntity;
import com.example.dou2204.entity.VideoEntity;
import com.example.dou2204.entity.VideoRoom;
import com.example.dou2204.live.LiveActivity;
import com.example.dou2204.login.LoginActivity;
import com.example.dou2204.roomdb.DataBaseUtils;
import com.example.dou2204.tuijian.TuijianViewModel;
import com.example.dou2204.utils.aspect.CheckLogin;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;

import java.util.ArrayList;
import java.util.List;

public class TuijianFragment extends BaseFragment<FragmentTuijianBinding, TuijianViewModel> {

    List<VideoEntity.DataBean> videos = new ArrayList<>();
    TuiVideoAdapter tuiVideoAdapter;
    int page = 1;
    int size = 30;
    int index = 0;
    long lastTime;

    List<CommentEntity.DataBean> comments = new ArrayList<>();
    CommentAdapter commentAdapter;

    public TuijianFragment() {
        // Required empty public constructor
    }


    @Override
    protected void initData() {
        viewModel.success.observe(this, new Observer<VideoEntity>() {
            @Override
            public void onChanged(VideoEntity entity) {
                if(entity.getCode()==200){
                    videos.clear();
                    videos.addAll(entity.getData());
                    tuiVideoAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.fail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.loveSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    ImageView ivDianzan = (ImageView) tuiVideoAdapter.getViewByPosition(index,R.id.iv_dianzan);
                    ivDianzan.setImageResource(R.drawable.ic_xihuanred);
                    TextView tvDianzan = (TextView) tuiVideoAdapter.getViewByPosition(index,R.id.tv_dianzan);
                    tvDianzan.setText(videos.get(index).getLike_count()+1+"");
                    videos.get(index).setDianzan(1);
                    ObjectAnimator animator = ObjectAnimator.ofFloat(ivDianzan, "scaleX", 1, 2, 1);
                    ObjectAnimator animator1 = ObjectAnimator.ofFloat(ivDianzan, "scaleY", 1, 2, 1);//缩放
                    ObjectAnimator alpha = ObjectAnimator.ofFloat(ivDianzan, "alpha", 1, 0, 1);//透明度
                    ObjectAnimator rotation = ObjectAnimator.ofFloat(ivDianzan, "rotation", -30, 30, 0);//旋转
                    //ObjectAnimator translationX = ObjectAnimator.ofFloat(ivDianzan, "translationX", 100, 0, 100);
                    //ObjectAnimator translationY = ObjectAnimator.ofFloat(ivDianzan, "translationY", 100, 0, 100);
                    AnimatorSet set = new AnimatorSet();
                    set.setDuration(2000);
                    set.play(animator).with(animator1).with(alpha).before(rotation);
                    set.start();
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.loveFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.noloveSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    ImageView ivDianZan = (ImageView) tuiVideoAdapter.getViewByPosition(index, R.id.iv_dianzan);
                    TextView tvDianZan = (TextView) tuiVideoAdapter.getViewByPosition(index, R.id.tv_dianzan);
                    ivDianZan.setImageResource(R.drawable.ic_xihuan);
                    tvDianZan.setText(videos.get(index).getLike_count()+"");
                    videos.get(index).setDianzan(0);
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.noloveFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.getcomSuccess.observe(this, new Observer<CommentEntity>() {
            @Override
            public void onChanged(CommentEntity entity) {
                if(entity.getCode()==200){
                    comments.clear();
                    comments.addAll(entity.getData());
                    commentAdapter.notifyDataSetChanged();
                }else {
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.getcomFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.comSuccess.observe(this, new Observer<CommentEntity>() {
            @Override
            public void onChanged(CommentEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    comments.add(0,entity.getData().get(0));
                    commentAdapter.notifyDataSetChanged();


                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.comFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });


    }

    @Override
    protected void initView() {
        tuiVideoAdapter = new TuiVideoAdapter(videos);
        binding.rv.setAdapter(tuiVideoAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rv.setLayoutManager(linearLayoutManager);
        viewModel.video(page,size);
        //仿抖音滑动分页
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.rv);
        //滑动到当前界面世，能够实现自动播放
        binding.rv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int position = linearLayoutManager.findFirstVisibleItemPosition();
                //为了后续实现关注点赞评论等操作，设置一个全局变量
                index = position;
                StandardGSYVideoPlayer gsy = (StandardGSYVideoPlayer) tuiVideoAdapter.getViewByPosition(position, R.id.gsy);
                if(gsy!=null){
                    gsy.startPlayLogic();
                }
            }
        });
        //点击item上的子控件
        tuiVideoAdapter.addChildClickViewIds(R.id.iv_add,R.id.iv_dianzan,R.id.iv_pinglun,R.id.iv_fenxiang,R.id.iv_close,R.id.iv_fasong,R.id.cl_quan,R.id.iv_shoucang,R.id.cl_live);
        tuiVideoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_add:
                        guanzhu(position);
                        break;
                    case R.id.iv_dianzan:
                        dianzan(position);
                        break;
                    case R.id.iv_pinglun:
                        binding.rv.setIntercept(false);//进行不拦截操作
                        pinglun(position);
                        break;
                    case R.id.iv_fenxiang:
                        fenxiang(position);
                        break;
                    case R.id.iv_close:
                        binding.rv.setIntercept(true);//恢复成拦截操作，因为评论框不显示了
                        closepinglun(position);
                        break;
                    case R.id.iv_fasong:
                        sendpinglun(position);
                        break;
                    case R.id.cl_quan:
                        quan(position);
                        break;
                    case R.id.iv_shoucang:
                        shoucang(position);
                        break;
                    case R.id.cl_live:
                        jin(position);//进入直播间
                        break;
                }
            }
        });
    }
    @CheckLogin
    private void jin(int position) {
        Intent intent = new Intent(getContext(), LiveActivity.class);
        intent.putExtra("video",videos.get(position));
        startActivity(intent);
    }

    @CheckLogin
    private void shoucang(int position) {
        VideoRoom room = new VideoRoom();
        room.setId(videos.get(position).getId());
        room.setAuthname(videos.get(position).getAuthname());
        room.setCaption(videos.get(position).getCaption());
        room.setHeadpath(videos.get(position).getHeadpath());
        room.setVideomainimg(videos.get(position).getVideomainimg());
        room.setVideopath(videos.get(position).getVideopath());
        room.setUsername(SPUtils.getInstance().getString("username"));
        DataBaseUtils.getInstance().getVideoDao().insertVideo(room);
        //修改收藏的图片
        ToastUtils.showLong("收藏成功");
        ImageView ivShoucang = (ImageView) tuiVideoAdapter.getViewByPosition(position, R.id.iv_shoucang);
        ivShoucang.setImageResource(R.drawable.ic_shoucangyellow);
    }

    @CheckLogin
    private void fenxiang(int position) {
        UMVideo video =new UMVideo(videos.get(position).getVideopath());
        video.setTitle(videos.get(position).getCaption());//视频的标题
        UMImage umImage = new UMImage(getContext(), videos.get(position).getVideomainimg());
        video.setThumb(umImage);//视频的缩略图
        video.setDescription(videos.get(position).getCaption());//视频的描述
        new ShareAction(getActivity()).withMedia(video)
                .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)//展示面板
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onError(SHARE_MEDIA media, Throwable throwable) {
                        ToastUtils.showLong("分享失败："+throwable.getMessage());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA media) {

                    }
                })
                .open();
    }

    private void quan(int position) {
        //找到播放器
        StandardGSYVideoPlayer gsyVideoPlayer = (StandardGSYVideoPlayer) tuiVideoAdapter.getViewByPosition(position, R.id.gsy);
        gsyVideoPlayer.startWindowFullscreen(getContext(),false,true);
    }

    @CheckLogin
    private void sendpinglun(int position) {
        //找到et控件，获取内容
        EditText etPing = (EditText) tuiVideoAdapter.getViewByPosition(position, R.id.et_pinglun);
        String trim = etPing.getText().toString().trim();
        if(trim.isEmpty()){
            ToastUtils.showLong("你可输入任意内容，然后在发送");
            return;
        }
        viewModel.comment(videos.get(position).getId(),trim);
        //清空编辑框内的内容
        etPing.setText("");
    }

    private void closepinglun(int position) {
        //找到评论的布局，让布局隐藏
        ConstraintLayout constraintLayout = (ConstraintLayout) tuiVideoAdapter.getViewByPosition(position, R.id.cl_pinglun);
         //添加动画效果
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.out);
        constraintLayout.startAnimation(animation);
        constraintLayout.setVisibility(View.GONE);
    }

    private void pinglun(int position) {
        //找到评论的布局，让布局显示
        ConstraintLayout constraintLayout = (ConstraintLayout) tuiVideoAdapter.getViewByPosition(position, R.id.cl_pinglun);
        constraintLayout.setVisibility(View.VISIBLE);
        //让焦点集中在editText中，方便后续去发送评论获取焦点
        EditText tvPing = (EditText) tuiVideoAdapter.getViewByPosition(position, R.id.et_pinglun);
        tvPing.requestFocus();
        //添加动画效果--从屏幕右侧缓慢滑出
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.in);
        animation.setInterpolator(new BounceInterpolator());//玻璃弹珠的效果
        constraintLayout.startAnimation(animation);
        //找到recycleview;
        RecyclerView rvPinglun = (RecyclerView) tuiVideoAdapter.getViewByPosition(position, R.id.rv_pinglun);
        commentAdapter = new CommentAdapter(R.layout.item_comment,comments);
        rvPinglun.setAdapter(commentAdapter);
        rvPinglun.setLayoutManager(new LinearLayoutManager(getContext()));
        viewModel.getcomment(videos.get(position).getId());
    }

    @CheckLogin
    private void dianzan(int position) {
        Log.d("sss", "dianzan:上次时间 ："+lastTime+"两次时间差："+(System.currentTimeMillis()-lastTime)+"毫秒");
        //如何解决不小心出现的连点问题
        if(System.currentTimeMillis()-lastTime>1000){//不是连点的情况
            if(videos.get(position).getDianzan()==0){//未点赞过
                viewModel.love(videos.get(position).getId());
            }else{//点赞过
                //执行取消点赞的操作
                viewModel.nolove(videos.get(position).getId());
            }
            lastTime = System.currentTimeMillis();
        }else {
            lastTime = System.currentTimeMillis();
        }


    }

    @CheckLogin
    private void guanzhu(int position) {
        /*//判断当前APP是否有用户登录，有---继续执行后续操作，    没有---进行登录
        if(SPUtils.getInstance().getString("token").isEmpty()){//没有登录
            startActivity(new Intent(getContext(), LoginActivity.class));
        }*/
        viewModel.guanzhu(videos.get(position).getAuthname());
        viewModel.guanzhuSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    ImageView ivAdd = (ImageView) tuiVideoAdapter.getViewByPosition(index, R.id.iv_add);//找到关注图标，
                    //ivAdd.setVisibility(View.GONE);//让关注图标消失//改成添加动画的效果
                    ivAdd.setImageResource(R.drawable.ic_duigou);
                    Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.alpha);
                    ivAdd.startAnimation(animation);
                    videos.get(index).setGuanzhu(1);
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.guanzhuFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong("请求失败："+s);
            }
        });
    }

    @Override
    protected int bindLayout() {
        return R.layout.fragment_tuijian;
    }

    @Override
    protected Class<TuijianViewModel> getViewModel() {
        return TuijianViewModel.class;
    }
    //防止内存泄漏
    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume(true);//继续播放
    }
}